package entity

import (
	"database/sql"
	"encoding/json"
	"kop/pb"
	"time"
)

type Mail struct {
	ID         int32       `gorm:"primary_key;AUTO_INCREMENT"`
	RoleID     int32       `gorm:"index"`
	FromType   pb.MailFrom `gorm:"type:smallint"`
	Title      string      `gorm:"size:255"`
	Content    string
	Attachment sql.NullString `gorm:"type:jsonb" json:"-"`
	Read       bool
	CreatedAt  time.Time
	UpdatedAt  time.Time

	AttachmentStruct *pb.Attachment `sql:"-"`
}

func (m *Mail) AfterFind() error {

	if m.Attachment.Valid {
		m.AttachmentStruct = &pb.Attachment{}
		return json.Unmarshal([]byte(m.Attachment.String), m.AttachmentStruct)
	}

	return nil
}

func (m *Mail) BeforeSave() error {

	if m.AttachmentStruct != nil {
		var b, _ = json.Marshal(m.AttachmentStruct)
		return m.Attachment.Scan(b)
	}

	return nil
}

func (m *Mail) BeforeUpdate() error {

	if m.AttachmentStruct != nil {
		var b, _ = json.Marshal(m.AttachmentStruct)
		return m.Attachment.Scan(b)
	}

	return nil
}
